<template>
	<view class="content">
		<el-form id="pdfDom" :model="productInfo" ref="proFormRef" label-position="top" :rules="rules">
			<!-- <el-form-item v-if="!isAdd">
				<el-row type="flex" justify="end">
					<el-button type="default" @click="editPro">
						<Icon class="mr-5rpx" icon="ep:edit" />{{ $t(`global.edit`) }}
					</el-button>
					<el-button type="default" @click="shareLink">
						<Icon class="mr-5rpx" icon="ep:share" />{{ $t(`global.share`) }}
					</el-button>
					<el-button v-if="!isAdd" type="danger" @click="deleteProduct">
						<Icon class="mr-5rpx" icon="ep:delete" />{{ $t(`global.delete`) }}
					</el-button>
				</el-row>
			</el-form-item> -->
			<el-form-item prop="goods" v-if="!isAdd">
				<el-text class="goods-title">{{ productInfo.goods }}</el-text>
			</el-form-item>
			<el-collapse v-model="activeNames">
				<el-collapse-item name="1">
					<template #title>
						<span class="collapse-title">{{ $t(`productDetail.from.title`) }}</span>
					</template>
					<el-row>
						<el-col :span="24">
							<el-form-item required :label="$t(`productDetail.from.id`)" prop="number">
								<span v-if="!isEdit && !isAdd">{{ productInfo.number }}</span>
								<el-input v-model="productInfo.number" v-else />
							</el-form-item>
						</el-col>
						<el-col :span="24">
							<el-form-item :label="$t(`productDetail.from.productName`)" prop="goods">
								<span v-if="!isEdit && !isAdd">{{ productInfo.goods }}</span>
								<el-input v-model="productInfo.goods" v-else />
							</el-form-item>
						</el-col>
						<el-col :span="24">
							<el-form-item :label="$t(`productDetail.from.specification`)" prop="specification">
								<span v-if="!isEdit && !isAdd">{{ productInfo.specification }}</span>
								<el-input v-model="productInfo.specification" v-else />
							</el-form-item>
						</el-col>
						<el-col :span="24">
							<el-form-item :label="$t(`productDetail.from.measurementUnit`)" prop="unit">
								<dict-tag v-if="!isEdit && !isAdd" :type="DICT_TYPE.HKB_GOODS_UNIT"
									:value="productInfo.unit" />
								<el-select v-model="productInfo.unit" :placeholder="$t(`global.select`)" clearable
									v-else>
									<el-option v-for="dict in getStrDictOptions(DICT_TYPE.HKB_GOODS_UNIT)"
										:key="dict.value + ''" :label="dict.label" :value="dict.value" />
								</el-select>
							</el-form-item>
						</el-col>
					</el-row>
					<el-divider border-style="dotted" />
					<el-form-item :label="$t(`productDetail.from.productClass`)" prop="goodsType">
						<dict-tag v-if="!isEdit && !isAdd" :type="DICT_TYPE.HKB_GOODS_TYPE"
							:value="productInfo.goodsType" />
						<el-select v-model="productInfo.goodsType" :placeholder="$t(`global.select`)" clearable v-else>
							<el-option v-for="dict in getStrDictOptions(DICT_TYPE.HKB_GOODS_TYPE)"
								:key="dict.value + ''" :label="dict.label" :value="dict.value" />
						</el-select>
					</el-form-item>
					<el-divider border-style="dotted" />
					<el-form-item :label="$t(`productDetail.from.description`)" prop="comment" v-if="showDetail">
						<span v-if="!isEdit && !isAdd" v-html="productInfo.comment"></span>
						<!--富文本编辑器组件-->
						<!-- <Editor v-model="productInfo.comment" v-else :toolConfig="toolbarConfig" style="width: 100%"
							height="300rpx" /> -->
					</el-form-item>
					<el-divider border-style="dotted" />
					<el-row>
						<el-col :span="24">
							<el-form-item :label="$t(`productDetail.from.accessory`)" prop="id">
								<el-row :gutter="10" style="width: 100%;">
									<el-col :span="12" v-for="(element, index) in fileDetailList">
										<el-image v-if="element.name.endsWith('jpg') ||
											element.name.endsWith('png') ||
											element.name.endsWith('jpeg')
										" :src="element.url" alt="" :preview-src-list="[element.url]" class="file-image" fit="cover"
											:preview-teleported="true" />
										<el-image v-else :src="fileImage" class="file-image file" fit="contain" />
									</el-col>
									<el-col :span="12">
										<el-upload v-if="isEdit || isAdd" action="#" list-type="picture-card"
											:file-list="fileDetailList" :auto-upload="false" :multiple="true"
											:show-file-list="false" :on-change="onchangeFile">
											<el-icon>
												<Plus />
											</el-icon>
										</el-upload>
									</el-col>
								</el-row>
							</el-form-item>
						</el-col>
						<el-col :span="24" v-if="!isAdd">
							<el-form-item :label="$t(`productDetail.from.barCode`)" prop="qrcode">
								<el-row :gutter="10" style="width: 100%;">
									<el-col :span="12">
										<el-image :preview-src-list="['data:image/jpeg;base64,' + productInfo.qrcode]"
											:src="'data:image/jpeg;base64,' + productInfo.qrcode" class="file-image"
											:preview-teleported="true" />
									</el-col>
								</el-row>
							</el-form-item>
						</el-col>
					</el-row>
				</el-collapse-item>
			</el-collapse>
		</el-form>
		<el-row type="flex" justify="center" class="guding">
			<el-button type="primary" @click="editPro" v-if="!isEdit">{{ $t(`global.edit`) }}</el-button>
			<el-button type="primary" v-show="isEdit || isAdd" :loading="buttonLoading" @click="uploadFile">{{
				$t(`global.verify`) }}</el-button>
			<el-button @click="cacel">{{ $t(`global.cancel`) }}</el-button>
		</el-row>
	</view>
	<el-dialog v-model="shareDialog" @closed="cacelShare">
		<el-input v-model="shareLinks" />
		<el-row type="flex" justify="center" style="margin-top: 20px">
			<el-button type="primary" @click="copyLink">复制链接</el-button>
			<el-button @click="cacelShare">{{ $t(`global.cancel`) }}</el-button>
		</el-row>
	</el-dialog>

	<uni-popup ref="popup" background-color="#fff" border-radius="10px 10px 0 0">
		<uni-row class="demo-uni-row">
			<uni-col :span="24">
				<el-button type="info" :icon="Share" text @click="shareLink">&nbsp&nbsp&nbsp&nbsp{{ $t(`global.share`)
					}}</el-button>
			</uni-col>
			<uni-col :span="24" style="margin-top: 10px;">
				<el-button type="info" :icon="Delete" text @click="deleteProduct">&nbsp&nbsp&nbsp&nbsp{{
					$t(`global.delete`)
					}}</el-button>
			</uni-col>
		</uni-row>
	</uni-popup>
</template>
<script setup lang="ts">
import { Delete, Share, Plus } from '@element-plus/icons-vue'
import { ref } from 'vue'
import * as productApi from '@/service/api/hkb/product'
import * as fileUpload from '@/service/api/infra/file'
import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'
import type { goodsVO } from '../types'
import type { FormInstance, FormRules } from 'element-plus'
import Storage from "@/modal/useStorage";
import i18n from '@/main'
import { REFRESH_CONFIG, getServiceEnvConfig } from '@/config'
const { url } = getServiceEnvConfig(import.meta.env)
onLoad(() => {
	const productDetail = Storage.get('productDetail')
	isAdd.value = productDetail.isAdd
	isEdit.value = productDetail.isEdit
	if (isAdd.value) {
		uni.setNavigationBarTitle({
			title: i18n.global.locale === 'zh' ? '新增商品详情' : 'ADDPRODUCT'
		})
	} else {
		uni.setNavigationBarTitle({
			title: i18n.global.locale === 'zh' ? '商品详情' : 'PRODUCTDETAIL'
		});
	}
	if (productDetail.product) {
		initFormValue(productDetail.product)
	}
})

const popup = ref()
onNavigationBarButtonTap(async (e) => {
	popup.value.open('bottom');
})


// defineOptions({ name: 'productDetail' })
const isAdd = ref(false)
const isEdit = ref(false)

const message = useMessage() // 消息弹窗

const emits = defineEmits(['submitUpdate', 'update:modelValue'])

const showDetail = ref(true)
import fileImage from '@/static/images/file.png'
const fileDetailList = ref<any[]>([])
const buttonLoading = ref(false) //按钮的加载
const activeNames = ref('1')
const flag = ref(false)
const shareDialog = ref(false)
const shareLinks = ref('')

const initForm = ref<goodsVO>({
	id: undefined,
	number: undefined,
	goods: '',
	specification: '',
	unit: '',
	qrcode: '',
	goodsFiles: [],
	goodsType: '',
	coverpath: '',
	comment: ''
})
const productInfo = ref<goodsVO>({
	id: undefined,
	number: undefined,
	goods: '',
	specification: '',
	unit: '',
	qrcode: '',
	goodsFiles: [],
	goodsType: '',
	coverpath: '',
	comment: ''
})
const rules = reactive<FormRules<goodsVO>>({
	number: [
		{ required: true, message: '请输入商品编号', trigger: 'blur' },
		{ min: 3, max: 20, message: '长度在3-20之间', trigger: 'blur' },
	],
	goods: [
		{
			required: true,
			message: '请输入商品品名',
			trigger: 'blur',
		},
	],
	specification: [
		{
			required: true,
			message: '请输入商品规格',
			trigger: 'blur',
		},
	],
	unit: [
		{
			required: true,
			message: '请选择商品单位',
			trigger: 'change',
		},
	],
	goodsType: [
		{
			required: true,
			message: '请选择产品类别',
			trigger: 'change',
		}
	]
})
const proFormRef = ref<FormInstance>()

const initFormValue = (val: any) => {
	proFormRef.value?.resetFields()
	productInfo.value = JSON.parse(JSON.stringify(val))
	fileDetailList.value = JSON.parse(
		JSON.stringify(productInfo.value).replaceAll('filePath', 'url').replaceAll('fileName', 'name')
	).goodsFiles
	productInfo.value.goodsFiles = []
}

defineExpose({
	initFormValue
})

import { IToolbarConfig } from '@wangeditor/editor'
import { isValidDatePickType } from 'element-plus/es/utils'
import { Navigate } from "@/utils";
const toolbarConfig: Partial<IToolbarConfig> = {
	excludeKeys: [
		'uploadVideo', // 排除菜单组，写菜单组 key 的值即可
		"group-video",
		'group-image',
		'emotion',
		'todo',
		'insertLink',
		'insertTable',
		'divider',
		'codeBlock'
	]
}

/** 编辑商品 **/
const editPro = () => {
	isEdit.value = true
	isAdd.value = false
}


//关闭弹窗
const cacel = () => {
	Navigate.to('/pages/hkb/product/product')
}

/** 返回表单信息信息 **/
const submitUpdate = async () => {
	await proFormRef.value?.validate(async (valid) => {
		if (valid) {
			buttonLoading.value = true
			if (productInfo.value.id) {
				await productApi
					.editProduct(productInfo.value)
					.then((res) => {
						if (res) {
							message.success('修改成功')
						} else {
							message.warning('修改失败')
						}
					})
					.finally(() => ((buttonLoading.value = false), cacel()))
			} else {
				await productApi
					.addProduct(productInfo.value)
					.then((res) => {
						if (res) {
							message.success('新增成功')
						} else {
							message.warning('新增失败')
						}
					})
					.finally(() => ((buttonLoading.value = false), cacel()))
			}
		}
	})
}

/** 上传文件 **/
const uploadFile = async () => {
	proFormRef.value?.validate(async (valid: boolean) => {
		if (valid) {
			if (fileDetailList.value.length > 0) {
				let formdata = new FormData()
				fileDetailList.value.map((item: any) => {
					if (item.raw) {
						formdata.append('files', item.raw)
					} else {
						item = JSON.parse(
							JSON.stringify(item).replaceAll('url', 'filePath').replaceAll('name', 'fileName')
						)
						productInfo.value.goodsFiles.push(item)
					}
				})
				if (flag.value) {
					const res = await fileUpload.updateFileBatch(formdata)
					flag.value = false
					let data = res.data.data
					data.map((item: any) => {
						let obj = {
							fileName: '',
							filePath: '',
							fileType: ''
						}
						obj.fileName = item.name
						obj.fileType = item.type
						obj.filePath = url + '/' + item.url
						productInfo.value.goodsFiles.push(obj)
					})
				}
			}
			submitUpdate()
		}
	})
}

/** 新增时删除附件 **/
const handleRemove = (index: number) => {
	fileDetailList.value.splice(index, 1)
}

/** 添加文件到文件列表 **/
const onchangeFile = (file: any) => {
	fileDetailList.value.push(file)
	flag.value = true
}


/** 删除 **/
const deleteProduct = async () => {
	try {
		// 二次确认
		await message.confirm('确认要立即删除这条数据吗?', '温馨提示')
		// 提交执行
		productApi.deleteProduct(productInfo.value.id).then((res) => {
			if (res) {
				message.success('删除成功')
			} else {
				message.warning('删除失败')
			}
		}).finally(() => (cacel(), emits('submitUpdate')))
	} catch (error) { }
}

/** 分享链接 **/
const shareLink = () => {
	// shareDialog.value = true
	shareLinks.value = window.location.href + '?shareId=' + productInfo.value.id
	uni.showModal({
		content: shareLinks.value,//模板中提示的内容
		confirmText: '复制内容',
		success: () => {//点击复制内容的后调函数
			//uni.setClipboardData方法就是讲内容复制到粘贴板
			uni.setClipboardData({
				data: shareLinks.value,//要被复制的内容
				success: () => {//复制成功的回调函数
					uni.showToast({//提示
						title: '复制成功'
					})
				}
			});
		}
	});
}

/** 取消分享 **/
const cacelShare = () => {
	shareDialog.value = false
}

// /** 复制链接 **/
// const copyLink = () => {
//
// }
/** 下载 **/
const handleDownload = (url: any) => {
	window.open(url)
}

</script>

<style scoped lang="scss">
.content {
	//height: 100vh;
	background: #fff;
	padding: 0 20rpx;
}

.goods-title {
	color: #000;
	font-size: 42rpx;
	margin: 20rpx 0 0;
}

.collapse-title {
	color: #000;
	font-size: 25rpx;
	font-weight: 600;
}


.image-box {
	position: relative;
	width: 180rpx;
	height: 148rpx;
	margin-right: 10rpx;

	&:hover .hover-box {
		display: block;

		.input {
			color: #fff
		}
	}
}

.guding {
	position: fixed;
	bottom: 10px;
	right: 50px;
}

::v-deep .uni-popup__wrapper {
	padding: 10px;
}

.file-image {
	width: 100%;
	height: 300rpx;
	border: 1rpx solid #ccc;
	display: flex;
	align-items: center;
	justify-content: center;
	cursor: pointer;
	margin-bottom: 20rpx;

	&.file ::v-deep(.el-image__inner) {
		width: auto;
		padding: 0 100rpx;
	}
}

.hover-box {
	display: none;
	position: absolute;
	top: 0;
	background: #00000090;
	height: 150rpx;
	width: 182rpx;
	box-sizing: border-box;
	padding: 10rpx;

	::v-deep(.input) {
		margin-bottom: 60rpx;
	}
}
</style>
